package com.xhh.learning.record.threadpool;

import java.util.concurrent.*;

/**
 * 类名： ThreadPoolDemo
 * 描述：
 * 公司： 北京海鑫科金高科技股份有限公司
 * 作者： hejianhui
 * 版本： V1.0
 * 创建时间:  2019/2/19 9:48
 * 最后修改时间:  2019/2/19 9:48
 */
public class ThreadPoolDemo {

    public static void main(String[] args) throws InterruptedException, TimeoutException, ExecutionException {
        long t0 = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        Future<String> test1 = executorService.submit(test1());
        Future<String> test2 = executorService.submit(test2());
        Future<String> test3 = executorService.submit(test3());
        Future<String> test4 = executorService.submit(test4());
        long t1 = System.currentTimeMillis();
        long t2 = System.currentTimeMillis();

        String s1 = test1.get(1, TimeUnit.SECONDS);
        String s2 = test2.get(2, TimeUnit.SECONDS);
        String s3 = test3.get(2, TimeUnit.SECONDS);
        String s4 = test4.get(3, TimeUnit.SECONDS);
        System.out.println("s1="+s1+",s2="+s2+",s3="+s3+",s4="+s4);

        long t3 = System.currentTimeMillis();

        System.out.println("t1-t0="+(t1-t0)+",t2-t1="+(t2-t1)+",t3-t2="+(t3-t2));
    }

    private static Callable<String> test1(){
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    Thread.sleep(1000);
                    return "test1";
                } finally {
                }
            }
        };
    }

    private static Callable<String> test2(){
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    Thread.sleep(2000);
                    return "test2";
                } finally {
                }
            }
        };
    }

    private static Callable<String> test3(){
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    Thread.sleep(3000);
                    return "test3";
                } finally {
                }
            }
        };
    }

    private static Callable<String> test4(){
        return new Callable<String>() {
            @Override
            public String call() throws Exception {
                try {
                    Thread.sleep(4000);
                    return "test4";
                } finally {
                }
            }
        };
    }

}
